import { useQuery } from 'react-query';
import { request } from '@/request';
import { TGroup } from '@/types';
import { PlusIcon, SettingIcon, BillIcon, AddIcon } from '@/components/icons';
import GroupSetting from './GroupSetting';
import { useGlobalVar } from '@/hooks';
import { useHistory } from 'react-router-dom';
import GroupShare from '@/views/Editors/GroupShare';
import GroupJoin from '@/views/Editors/GroupJoin';

type TGroupRes = {
   list: Array<TGroup>;
};

const GroupManager = () => {
   const { groupId, user } = useGlobalVar();
   const history = useHistory();

   // 获取分组
   const { data: groups, refetch } = useQuery<Array<TGroup>>(
      'groups',
      async () => {
         const res = await request<TGroupRes>('/groups');
         return res.data.list;
      }
   );

   if (groups === undefined) return <div>Loading...</div>;

   const group = groups.find((item) => item._id === groupId);

   return (
      <div className="flex justify-between">
         {groups.length === 0 ? (
            <div
               className="btn btn_icon"
               onClick={() => {
                  history.push('/group');
               }}
            >
               <PlusIcon type="white" size={16} />
               <span>添加分组</span>
            </div>
         ) : (
            <GroupSetting
               refresh={refetch}
               groups={groups}
               handler={
                  group ? (
                     <div className="shadow-lg bg-indigo-900 absolute py-1 px-4 rounded-r-lg top-3 -left-1 text-white flex items-center space-x-2">
                        <BillIcon type="white" size={20} />
                        <span>{group.group_name}</span>
                     </div>
                  ) : (
                     <div className="btn btn_icon bg-transparent border text-black">
                        <SettingIcon size={16} />
                        <span>选择分组</span>
                     </div>
                  )
               }
            />
         )}
         <div className="flex items-center space-x-3">
            {group && group.createdBy === user._id && (
               <GroupShare groupId={group._id} groupName={group.group_name} />
            )}
            <GroupJoin refetch={refetch}/>
            {group && (
               <AddIcon type="primary" onClick={() => history.push('/group')} />
            )}
         </div>
      </div>
   );
};

export default GroupManager;
